package com.wujp.xml.template.core.loader;

import com.allinfinance.common.template.service.utils.FileUtil;
import com.allinfinance.common.template.service.utils.StringUtil;
import com.wujp.xml.template.core.interfaces.TemplateConfigurationLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 文件模板加载, 加载过程是线程安全的
 * @author: wujp
 * @create: 2024-12-17 19:40
 */
@Slf4j
public class MultiFileTemplateConfigurationLoader implements TemplateConfigurationLoader {

    private String filePath;

    private String suffix = ".ftl";

    @Override
    public Configuration loadTemplateConfiguration() {
        File fileDirectory = null;
        List<Template> templates = new ArrayList<Template>();
        if (StringUtil.isBank(filePath)) {
            throw new RuntimeException("filePath field must not be null");
        }
        fileDirectory = new File(filePath);
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        if (fileDirectory.exists() && fileDirectory.isDirectory()) {
            File[] files = fileDirectory.listFiles();
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(suffix)) {
                    try {
                        String template = FileUtil.readFile(file);
                        if (StringUtil.isNotBank(template)) {
                            template = template.replace("\r\n", "").replace("\r", "");
                            stringTemplateLoader.putTemplate(file.getName().substring(0, file.getName().indexOf(suffix)), template);
                        }
                    } catch (IOException e) {
                        log.error("MultiFileTemplateLoader load templates error.", e);
                        throw new RuntimeException(e);
                    }
                }
            }
            configuration.setTemplateLoader(stringTemplateLoader);

        } else {
            throw new RuntimeException(String.format("filePath=%s  not exists or not be directory "));
        }
        return configuration;
    }

    @Override
    public int priority() {
        return 100;
    }
}
